<script lang="ts" setup>
import codeComponent from './code/index.vue'
import { reactive, ref, onMounted } from "vue"
import { useRouter } from "vue-router"
import { useUserStore } from "@/store/modules/user"
import { ElMessage, type FormInstance, type FormRules } from "element-plus"
import { User, Lock, Key, Picture, Loading } from "@element-plus/icons-vue"
import { getLoginCodeApi, getUserInfoApi } from "@/api/login"
import { LoginRequestData } from "@/api/login/types/login"
// import ThemeSwitch from "@/components/ThemeSwitch/index.vue"
// import { useTheme } from "@/hooks/useTheme"

import { setPassword, getPassword } from "@/utils/cache/local-storage"
import { encryptAES, decryptAES } from "@/utils/secret"
import { formatAxis } from '@/utils/index'

onMounted(() => {
  const pswd = getPassword()
  if (pswd != null) {
    const secretText = decryptAES(pswd.toString())
    loginFormData.loginName = secretText.split(",")[0]
    loginFormData.password = secretText.split(",")[1]
    rememberMe.value = true
  }
})
/** Layout 布局响应式 */
/** router */
const router = useRouter()
/** 登录表单元素的引用 */
const loginFormRef = ref<FormInstance | null>(null)
/** 登录按钮 Loading */
const loading = ref(false)
/** 验证码图片 URL */
const codeUrl = reactive({
  originalImage: '',
  slideImage: '',
})
/** 记住我 */
const rememberMe = ref(false)
/** 登录表单数据 */
const loginFormData = reactive({
  requestTime: 0,
  loginName: "",
  password: "",
  verifyKey: "",
  pointX:null
})
/** 登录表单校验规则 */
const loginFormRules: FormRules = {
  loginName: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
  ]
}
/** 验证码唯一值 */
const snowflakeId = ref("")

/** 登录逻辑 */
const handleLogin = () => {
      loading.value = true
      useUserStore()
        .login(loginFormData)
        .then(async () => {
          if (rememberMe.value) {
            setPassword(encryptAES(loginFormData.loginName + "," + loginFormData.password))
          }else  setPassword(encryptAES(loginFormData.loginName))
          showCode.value=false
          // const { data } = await getUserInfoApi()
          // if (data.root !== 1) {
          //   useUserStore().logout()
          //   ElMessage.error('暂无权限，请联系管理员')
          //   return
          // }
          router.push({ path: "/" })
          ElMessage.success(`${formatAxis(new Date())},欢迎回来！`)
        })
        .catch(() => {
          createCode()
          // loginFormData.pwd = ""
        })
        .finally(() => {
          loading.value = false
        })
}
/** 创建验证码 */
const createCode = () => {
  // 生成随机数
  loginFormData.verifyKey = useUserStore().createUniqueCode()
  let data = {
    verifyKey: loginFormData.verifyKey
  }
  getLoginCodeApi(data).then((res: any) => {
    const { originalImage, slideImage } = res.data
    let imgHader = 'data:image/png;base64,'
    codeUrl.originalImage = imgHader + originalImage
    codeUrl.slideImage = imgHader + slideImage
  })
}
/** 初始化验证码 */
createCode()

const showCode = ref(false)
const openCode = () => {
  loginFormRef.value?.validate((valid: boolean, fields) => {
    if (valid) {
      showCode.value=true
    }})
}
const successCode=(e)=>{
  loginFormData.pointX=e
  handleLogin()
}
</script>

<template>
  <div class="main">
    <div class="login-container">
      <div class="login-card-border">
        <div class="login-card">
          <div class="title aic ailgn-center center">
            <!-- <img src="@/assets/layouts/logo.png" style="height: 55px; width: 70px" /> -->
            <div class="fs30 ml20" style="color: #409eff;">企业通CRM</div>
          </div>
          <div class="content">
            <el-form ref="loginFormRef" :model="loginFormData" :rules="loginFormRules" @keyup.enter="openCode">
              <el-form-item prop="loginName">
                <el-input v-model.trim="loginFormData.loginName" placeholder="用户名" type="text" tabindex="1"
                  :prefix-icon="User" size="large" />
              </el-form-item>
              <el-form-item prop="password">
                <el-input v-model.trim="loginFormData.password" placeholder="密码" type="password" tabindex="2"
                  :prefix-icon="Lock" size="large" show-password />
              </el-form-item>
              <div>
                <el-checkbox v-model="rememberMe">记住我</el-checkbox>
                <el-button :round="true" :loading="loading" type="primary" size="large" @click.prevent="openCode">登
                  录</el-button>
              </div>
            </el-form>
          </div>
        </div>
        <el-dialog v-model="showCode"  width="350" title="滑动登录验证" >
          <codeComponent  v-if="showCode"  :data="codeUrl" @success="successCode"></codeComponent>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.main {
  height: 100%;
  width: 100%;
  position: relative;
  background-image: url("@/assets/png/bannner.png");
  background-repeat: no-repeat;
  background-size: cover;
}

.kf {
  position: absolute;
  top: 3vh;
  right: 10vw;
  white-space: nowrap;
  color: #888;
}

.login-container {
  display: flex;
  justify-content: center;
  // margin-right: 200px;
  align-items: center;
  // vertical-align: middle;
  // float: right;
  width: 100%;
  // margin: 100px 80px 0 0;
  height: 100vh;

  .theme-switch {
    position: fixed;
    top: 5%;
    right: 5%;
    cursor: pointer;
  }

  .login-card {
    width: 480px;
    // opacity: 0.9;
    border-radius: 20px;
    box-shadow: 0 0 10px #dcdfe6;
    background-color: #fff;
    overflow: hidden;
    margin: auto;
    padding: 50px;

    .title {
      padding-bottom: 20px;
      font-size: 24px;

      img {
        height: 100%;
      }
    }

    .content {

      :deep(.el-input-group__append) {
        padding: 0;
        overflow: hidden;

        .el-image {
          width: 100px;
          height: 40px;
          padding: 2px;
          border-left: 0px;
          user-select: none;
          cursor: pointer;
          text-align: center;
        }
      }

      .el-button {
        width: 100%;
        margin-top: 10px;
      }
    }
  }

  .login-card-border2 {
    width: 520px;
    height: 540px;
    display: flex;
    // opacity: 0.2;
    justify-content: center;
    align-items: center;
    border-radius: 20px;
    box-shadow: 0 0 10px #dcdfe6;
    background-color: #fff;
    overflow: hidden;
  }
}

.top-container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100px;
  background-color: #fff;
  box-shadow: 0 0 10px #dcdfe6;
  font-size: 14px;
  margin-bottom: 10px;
  opacity: 0.8;

  img {
    width: 165px;
    margin-left: 200px;
  }

  .line {
    border-right: 1px solid grey;
    height: 60px;
  }

  .title {
    width: 100px;
    text-align: center;
    margin-left: 10px;
    white-space: nowrap;
  }

  .doc {
    width: 100px;
    white-space: nowrap;
  }
}

.codeBox {
  width: 300px;
  height: 200px;
  background: #fff;
  position: fixed;
  top: calc(50% - 100px);
  left: calc(50% - 150px);
  z-index: 999;
}


/* 媒体查询（手机） */
@media screen and (max-width: 768px) {
  .login-card {
    width: 100vw !important;
    height: 100vh;
    border-radius: 0 !important;
    padding: 20px !important;

    .title {
      justify-content: center;

      img {
        display: none;
      }

      div {

        font-size: 24px;
      }
    }
  }

}

// /* 媒体查询（平板） */
// @media screen and (min-width: 768px) and (max-width: 996px) {
//   .top-container img {
//     width: 1000px;
//   }
// }</style>
